package logic

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"furni-mgr/models/mysql"
	"furni-mgr/models/redis"
	"time"

	"furni-mgr/furnirpc/furnirpc"
	"furni-mgr/furnirpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FurnitureListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFurnitureListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FurnitureListLogic {
	return &FurnitureListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 家具列表方法
func (l *FurnitureListLogic) FurnitureList(in *furnirpc.FurnitureListRequest) (*furnirpc.FurnitureListResponse, error) {
	// todo: add your logic here and delete this line
	var list []*furnirpc.FurnitureList
	var err error

	key := fmt.Sprintf("Furniture_List")

	result, _ := redis.Rdb.Get(redis.Ctx, key).Result()

	if result == "" {
		list, err = mysql.FurnitureList(mysql.DB)
		if err != nil {
			return nil, errors.New("列表失败")
		}
		marshal, _ := json.Marshal(list)
		redis.Rdb.Set(redis.Ctx, key, marshal, time.Hour*1)
	} else {
		json.Unmarshal([]byte(result), &list)
	}

	return &furnirpc.FurnitureListResponse{
		List: list,
	}, nil
}
